package com.g0dkar.leet.core.rest.actions;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.view.Results;

import com.g0dkar.leet.core.Leet;
import com.g0dkar.leet.util.common.StringUtils;
import com.g0dkar.leet.util.ognl.typeConversion.primitive.CollectionConverter;

public abstract class AbstractRestAction {
	protected Leet application;
	protected Result result;
	protected HttpServletRequest request;
	
	private static final String IGNORE_PREFIX = "_";
	
	public AbstractRestAction(Leet application, Result result, HttpServletRequest request) {
		this.application = application;
		this.result = result;
		this.request = request;
	}
	
	public void restReturn(Result result, String format, Object responseObject) {
		format = StringUtils.isBlank(format) ? "json" : format;
		
		if (format.equalsIgnoreCase("json")) {
			result.use(Results.json()).withoutRoot().from(responseObject).serialize();
		}
		else if (format.equalsIgnoreCase("xml")) {
			result.use(Results.xml()).from(responseObject).serialize();
		}
	}
	
	public Map<String, Object> buildEntityValuesMap(String prefix) {
		String keyName;
		String[] parameterValues;
		Map parameterMap = request.getParameterMap();
		Map<String, Object> values = new HashMap<String, Object>();
		boolean isEmptyPrefix = StringUtils.isBlank(prefix);
		
		if (!isEmptyPrefix) {
			prefix = prefix.toLowerCase();
		}
		
		for (Object key : parameterMap.keySet()) {
			keyName = key.toString();
			
			if (keyName.toLowerCase().startsWith(IGNORE_PREFIX)) {
				continue;
			}
			
			if (!isEmptyPrefix && keyName.toLowerCase().startsWith(prefix)) {
				keyName = keyName.substring(prefix.length() + 1);
			}
			
			parameterValues = request.getParameterValues(key.toString());
			
			if (parameterValues.length == 1) {
				values.put(keyName, parameterValues[0]);
			}
			else if (parameterValues.length > 1) {
				try {
					values.put(keyName, CollectionConverter.asStringArray(parameterValues));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		return values;
	}
}
